//
//  PayOrderViewController.m
//  dyseller
//
//  Created by 红喇叭 on 2017/8/17.
//  Copyright © 2017年 红喇叭. All rights reserved.
//

#import "PayOrderViewController.h"
#import "RemindView.h"
#import "PayOrderCell.h"

@interface PayOrderViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>{
    NSArray *_isUsed;//已使用
    NSArray *_noUsed;//未使用
    NSMutableArray *_data;
    UITextField *search;//搜索框
}
@property(nonatomic,strong)UITableView *tableView;

@end

@implementation PayOrderViewController

- (instancetype)initWith:(id)dic style:(int)style{
    self = [super init];
    if(self){
        _style = style;
        if(style == 0){
            _isUsed = dic[@"isUsed"];
            _noUsed = dic[@"noUsed"];
            _data = _isUsed.mutableCopy;
            _data = [self addkey:_data].mutableCopy;
            //显示全部
           // [self allthequery];
        }else if(style == 1){
            _data = ((NSArray*)dic).mutableCopy;
            _data = [self addkey:_data].mutableCopy;
        }else if(style == 2){
            _data = @[].mutableCopy;
            [_data addObject:dic];
            _data = [self addkey:_data].mutableCopy;
        }
//        if(_data.count<3){
//            self.tableView.scrollEnabled = NO;
//        }else{
//            self.tableView.scrollEnabled = YES;
//        }
    }
    return self;
}
- (void)dealloc{
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    [self.backBtn setImage:[UIImage imageNamed:@"logain_nav_icon_default.png"] forState:UIControlStateNormal];
    __weak typeof(self)weakself = self;
    self.view.backgroundColor = [UIColor whiteColor];
    self.tableView.backgroundColor = [UIColor whiteColor];
   
    if(_style == 0){
        [self shopOrderTableSet];// style =0 时是商品订单的table
    }else if(_style == 1){
        [self sreachStyleSet];//订单搜索界面设置
    }else if (_style == 2){
        [self addfooterView];
    }
    
    if(_style == 1 &&_data.count>0){
        UIView *topView = [[UIView alloc] initWithFrame:CGRectMake(0,0, SCREEN_W, 2)];
        topView.backgroundColor = UIColorFromRGB(0xdddddd);
        [self.view addSubview:topView];
        _tableView.frame = CGRectMake(0, 2, SCREEN_W, SCREEN_H-64-44);
        if(SCREEN_H == 812){
            _tableView.height = SCREEN_H - 89 -44;
        }
    }
}


- (void)viewWillDisappear:(BOOL)animated{
    [search resignFirstResponder];
}

#pragma  mark ========Style ========
//self.style == 0
- (void)shopOrderTableSet{
    self.tableView.frame = CGRectMake(0, GETHEIGHT(80), SCREEN_W, SCREEN_H-44-64-40);
    if(_isUsed.count>0||_noUsed.count>0){
        [self setTableViewHeader];
        self.tableView.hidden = NO;
    }else{
        self.tableView.hidden = YES;
        RemindView *remindView = [[RemindView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, SCREEN_H-44-64) remindString:@"暂无商品订单"];
        [self.view addSubview:remindView];
    }
    if(SCREEN_H == 812){
        _tableView.height -= 34;
    }

}

//_style == 1 时  搜索界面的设置
- (void)sreachStyleSet{
    search = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, GETWITH(600), 27)];
    search.backgroundColor = UIColorFromRGB(0xEBEBEB);
    search.font = font14;
    search.layer.cornerRadius = 5;
    search.layer.masksToBounds = YES;
    
    search.placeholder = @"订单号/手机号/用户ID";
    search.delegate = self;
    search.returnKeyType = UIReturnKeySearch;
    [search becomeFirstResponder];
    
    UIImageView *right = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"dingd_icon_default_nor.png"]];
    right.frame = CGRectMake(search.width-GETWITH(150), 0, GETWITH(32), GETWITH(32));
    if(SCREEN_W<375){
        right.x = search.width-GETWITH(160);
    }else{
        right.x = search.width-GETWITH(140);
    }
    right.centerY = search.centerY;
    [search addSubview:right];
    
    
    if(_orderStr.length>0){
        search.text = _orderStr;
        [self srerchData];
    }
    
    
    self.navigationItem.titleView = search;
    
    
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.frame = CGRectMake(0, 0, GETWITH(88), 44);
    [rightBtn setImage:[UIImage imageNamed:@"sousuo_nav_btn_default.png"] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(srerchData) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:rightBtn];
    if (@available(iOS 11, *)) {
        rightBtn.contentHorizontalAlignment =UIControlContentHorizontalAlignmentRight;
        [rightBtn setImageEdgeInsets:UIEdgeInsetsMake(0, 0,0,-1*SCREEN_W /375.0)];
        if(SCREEN_W<375)
            [rightBtn setImageEdgeInsets:UIEdgeInsetsMake(0, 0,0,-5*SCREEN_W /375.0)];
    }
    if(_fromVC==1){
        [self toreduce];
        self.tableView.height = SCREEN_H-64;
        if(SCREEN_H == 812){
            _tableView.height = SCREEN_H - 89;
        }
    }else if(_fromVC == 2){
        self.tableView.height = SCREEN_H-64;
        if(SCREEN_H == 812){
            _tableView.height = SCREEN_H - 89;
        }
    }else{
        
        if(_data.count>0){
            self.tableView.hidden = NO;
        }else{
            self.tableView.hidden = YES;
            RemindView *remindView = [[RemindView alloc] initWithFrame:CGRectMake(0, 0.5, SCREEN_W, SCREEN_H-44-64) remindString:@"暂无买单订单"];
            [self.view addSubview:remindView];
        }
    }
}
#pragma  mark ========核销提醒========
//核销成功提醒
- (void)updateAdress{
    __weak typeof(self)weakself = self;
    UIAlertController *alter = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"核销成功，是否继续核销其他订单" preferredStyle:UIAlertControllerStyleAlert];
    [alter addAction:[UIAlertAction actionWithTitle:@"是" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakself.navigationController popViewControllerAnimated:YES];
    }]];
    
    [alter addAction:[UIAlertAction actionWithTitle:@"否" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakself.navigationController popToRootViewControllerAnimated:YES];
    }]];
    
    [self presentViewController:alter animated:YES completion:nil];
}


#pragma  mark ========视图处理========
//tableView 懒加载
- (UITableView *)tableView{
    if(_tableView == nil){
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, SCREEN_H-64-44) style:UITableViewStylePlain];
        if(SCREEN_H == 812){
            _tableView.height = SCREEN_H - 89 -44;
        }
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.estimatedRowHeight = 200;
        
        [_tableView registerClass:[PayOrderCell class] forCellReuseIdentifier:@"PayOrderCell"];
        //UITableView去掉自带系统的分割线
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self.view addSubview:_tableView];
    }
    
    return _tableView;
}

- (void)addfooterView{
    self.tableView.height = SCREEN_H-64-50;
    if(SCREEN_H == 812){
        self.tableView.height = SCREEN_H-89-50;
    }
    UIView *footerV = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_H-64-50, SCREEN_W, 40)];
    [self.view addSubview:footerV];
    UIButton *close = [UIButton buttonWithType:UIButtonTypeCustom];
    
    [close setTitle:@"取消" forState:UIControlStateNormal];
    close.layer.cornerRadius = 8;
    close.layer.masksToBounds = YES;
    [close setBackgroundColor:UIColorFromRGB(0xe71a47)];
    __weak typeof(self)weakself = self;
    [close handleControlEvent:UIControlEventTouchUpInside withBlock:^(id sender) {
        [weakself.navigationController popViewControllerAnimated:YES];
    }];
    close.frame = CGRectMake(0, 0, SCREEN_W/2-10, 40);
    [footerV addSubview:close];
    
    UIButton *sure = [UIButton buttonWithType:UIButtonTypeCustom];
    sure.layer.cornerRadius = 8;
    sure.layer.masksToBounds = YES;
    [sure setBackgroundColor:UIColorFromRGB(0xe71a47)];
    [sure setTitle:@"核销" forState:UIControlStateNormal];
    [sure addTarget:self action:@selector(hexiao) forControlEvents:UIControlEventTouchUpInside];
    [sure setBackgroundColor:[UIColor orangeColor]];
    sure.frame = CGRectMake(SCREEN_W/2+10, 0, SCREEN_W/2-10, 40);
    [footerV addSubview:sure];
}


- (void)setTableViewHeader{
    
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, GETHEIGHT(80))];
    
    headView.backgroundColor = UIColorFromRGB(0xeeeeee);
    NSString *nousr = [NSString stringWithFormat:@"未使用(%ld)",_noUsed.count];
    UISegmentedControl *segmentVC  = [[UISegmentedControl alloc] initWithItems:@[@"已使用",nousr]];
    segmentVC.selectedSegmentIndex = 0;
    segmentVC.layer.masksToBounds = YES;               //    默认为no，不设置则下面一句无效
    
    segmentVC.layer.cornerRadius = 5;               //    设置圆角大小，同UIView
    
    segmentVC.layer.borderWidth = 0.5;                   //    边框宽度，重新画边框，若不重新画，可能会出现圆角处无边框的情况
    segmentVC.tintColor = UIColorFromRGB(0xe71a41);
    segmentVC.backgroundColor = [UIColor whiteColor];
    segmentVC.layer.borderColor = UIColorFromRGB(0xe71a41).CGColor; //     边框颜色
    
    //设置普通状态下(未选中)状态下的文字颜色和字体
    [segmentVC setTitleTextAttributes:@{NSFontAttributeName:font12,NSForegroundColorAttributeName:UIColorFromRGB(0xe71a41)} forState:UIControlStateNormal];
    //设置选中状态下的文字颜色和字体
    [segmentVC setTitleTextAttributes:@{NSFontAttributeName:font12,NSForegroundColorAttributeName: [UIColor whiteColor],} forState:UIControlStateSelected];
    
    [headView addSubview:segmentVC];
    segmentVC.sd_layout.leftSpaceToView(headView, GETWITH(30)).rightSpaceToView(headView, GETWITH(30)).centerYEqualToView(headView).heightIs(25);
    [segmentVC addTarget:self action:@selector(didClicksegmentedControlAction:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:headView];
}

-(void)didClicksegmentedControlAction:(UISegmentedControl *)seg{
    NSInteger Index = seg.selectedSegmentIndex;
    if(Index==0){
        [self completedThequery];
    }else{
        [self dontUseThequer];
    }
}


#pragma  mark ========网络请求========
//减少角标数字
- (void)toreduce{
    NSDictionary *dic = [userDefaults objectForKey:@"NocationList"];
    NSMutableArray *arr = dic.mutableCopy;
    
    NSMutableDictionary *newdic = ((NSDictionary *)arr[1]).mutableCopy;
    if([newdic[@"newItem"] intValue]>0){
        NSString *number = [NSString stringWithFormat:@"%d",[newdic[@"newItem"] intValue]-1];
        [[PPHttpRequsetData shareInstance] requestStyle:Request_POST URL:@"/ShopApi/Notice/unreadChange" isactive:YES parameter:@{@"number":number,@"flag":@"order"} successBlock:^(PPHttpRequest *request, id responseObj) {
            newdic[@"newItem"] = [NSString stringWithFormat:@"%d",[responseObj[@"order"] intValue]];
            arr[1] = newdic;
            [userDefaults setObject:arr forKey:@"NocationList"];
        } failBlock:^(PPHttpRequest *request, NSString *errMsg) {
            [AlertUtils showToastWithMessage:errMsg inView:self.view hideAfterDelay:2.0 beIndeter:NO];
        }];
    }
}

//搜索
- (void)srerchData{
    if(search.text.length<1){
        [AlertUtils showToastWithMessage:@"请输入查询条件" inView:self.view hideAfterDelay:2.0 beIndeter:NO];
        return;
    }
    [search resignFirstResponder];
    __weak typeof (self)weakself = self;
    [[PPHttpRequsetData shareInstance] requestStyle:Request_POST URL:@"/ShopApi/Order/orderList" parameter:@{@"keyWord":search.text} successBlock:^(PPHttpRequest *request, id responseObj) {
        NSArray *payOrder = responseObj[@"payOrder"];
        NSArray *isUsed = responseObj[@"goodsOrder"][@"isUsed"];
        NSArray *noUsed = responseObj[@"goodsOrder"][@"noUsed"];
        if(payOrder.count < 1 && isUsed.count<1 && noUsed.count < 1){
            [AlertUtils showToastWithMessage:@"您查询的条件没有匹配结果" inView:self.view hideAfterDelay:2.0 beIndeter:NO];
        }else{
            NSMutableArray *allArray = @[].mutableCopy;
            [payOrder enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                [allArray addObject:obj];
            }];
            
            [isUsed enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                [allArray addObject:obj];
            }];
            
            [noUsed  enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                [allArray addObject:obj];
            }];
            _data = allArray;
            _data = [weakself addkey:_data].mutableCopy;
            if(_data.count<3){
                weakself.tableView.scrollEnabled = NO;
            }else{
                weakself.tableView.scrollEnabled = YES;
            }
            [weakself.tableView reloadData];
        }
        
    } failBlock:^(PPHttpRequest *request, NSString *errMsg) {
        [AlertUtils showToastWithMessage:errMsg inView:self.view hideAfterDelay:2.0 beIndeter:NO];
    }];
    
}

//核销接口
- (void)hexiao{
    __weak typeof(self)weakself = self;
    NSDictionary *dic = _data.firstObject;
    [[PPHttpRequsetData shareInstance] requestStyle:Request_POST URL:@"/ShopApi/Scan/orderVerify" parameter:@{@"order_sn":dic[@"order_sn"],@"flag":@"1"} successBlock:^(PPHttpRequest *request, id responseObj) {
        [weakself updateAdress];
    } failBlock:^(PPHttpRequest *request, NSString *errMsg) {
        [AlertUtils showToastWithMessage:errMsg inView:self.view hideAfterDelay:2.0 beIndeter:NO];
    }];
    
}
#pragma  mark ========数据处理========

//为数组添加新的字段，来控制商品列表的显示
- (NSArray *)addkey:(NSArray *)array{
    NSMutableArray *arr = @[].mutableCopy;
    for (NSDictionary *dic in array) {
        NSMutableDictionary *newdic = dic.mutableCopy;
        [newdic setObject:@"1" forKey:@"isAN"];
        if(_style == 2 || _style==1){
            [newdic setObject:@"1" forKey:@"isAN"];
        }
        [arr addObject:newdic];
    }
    
    return arr;
}
//未完全已完成的总数
- (void)allthequery{
    _isUsed = [self addkey:_isUsed];
    _noUsed = [self addkey:_noUsed];
    _data = _isUsed.mutableCopy;
    [_noUsed enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [_data addObject:obj];
    }];
    [self.tableView reloadData];
}

- (void)completedThequery{
    _isUsed = [self addkey:_isUsed];
    
    _data = _isUsed.mutableCopy;
    
    [self.tableView reloadData];
    
}

- (void)dontUseThequer{
    
    _noUsed = [self addkey:_noUsed];
    _data = _noUsed.mutableCopy;
    
    [self.tableView reloadData];
    
}


#pragma mark -- UITableViewDataSoure UITabelViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _data.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
   
    PayOrderCell *cell=nil;
    if (cell==nil) {
        cell=[[PayOrderCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"PayOrderCell"];
    }else{
        while ([cell.contentView.subviews lastObject] != nil) {
            [(UIView*)[cell.contentView.subviews lastObject] removeFromSuperview];  //删除并进行重新分配
        }
    }
    cell.data = _data[indexPath.row];
    cell.anBtn.tag = indexPath.row;
    [cell.anBtn addTarget:self action:@selector(reloadS:) forControlEvents:UIControlEventTouchUpInside];
    
    cell.contentView.backgroundColor = [UIColor whiteColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
  
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSArray *goods = _data[indexPath.row][@"goods_list"];
    NSMutableDictionary *dic = _data[indexPath.row];
     NSDictionary *dicT = [userDefaults objectForKey:@"agentInfo"];
    if(goods.count > 0){
        if([dic[@"isAN"] isEqualToString:@"0"]){
            if([dicT[@"extend_fun"] rangeOfString:@"1"].location !=NSNotFound ||[dic[@"can_refund"] isEqualToString:@"1"]){
                return 210 + 60;
            }
            return 210;
        }else if([dic[@"isAN"] isEqualToString:@"1"]){
            CGFloat height = [self cellHeightGoods:goods];
            if([dicT[@"extend_fun"] rangeOfString:@"1"].location !=NSNotFound ||[dic[@"can_refund"] isEqualToString:@"1"]){
                 return 260 + 60 + height;
            }
            return 260 +10 + height;
        }
       
    }else if ([dic[@"can_refund"] isEqualToString:@"1"])
              return 180 + 50;
    return 180;

}

#pragma mark --UITextFiledDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    [self srerchData];
    return YES;
}

- (CGFloat)cellHeightGoods:(NSArray *)goods{
    CGFloat height = 0;
    for (NSDictionary *newdic in goods) {
        CGSize titleSize = [newdic[@"goods_name"] boundingRectWithSize:CGSizeMake(GETWITH(300), MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:font14 } context:nil].size;
             height += (titleSize.height +16);
       
    }
    return height;
}

//订单详情收起，展开的事件
- (void)reloadS:(UIButton *)btton{
    
     NSMutableDictionary *dic = ((NSDictionary *)(_data[btton.tag])).mutableCopy;
    if([dic[@"isAN"] isEqualToString:@"0"]){
        [dic setObject:@"1" forKey:@"isAN"];
       
    }else if([dic[@"isAN"] isEqualToString:@"1"]){
        [dic setObject:@"0" forKey:@"isAN"];
       
    }
    _data[btton.tag] = dic;
    NSIndexPath *indexPath=[NSIndexPath indexPathForRow:btton.tag inSection:0];
  
    [_tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationAutomatic];
}


@end
